import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/festival.dart';
import 'package:geomancy/models/festival_article_list_model.dart';
import 'package:geomancy/models/festival_list_model.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_loading_circle.dart';
import 'package:geomancy/widgets/common_shadow_text.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:go_router/go_router.dart';

class CalendarFestivalDescPage extends StatefulWidget {
  final FestivalItemModel festival;
  const CalendarFestivalDescPage({super.key, required this.festival});

  @override
  State<CalendarFestivalDescPage> createState() => _CalendarFestivalDescPageState();
}

class _CalendarFestivalDescPageState extends State<CalendarFestivalDescPage> {
  List<Article> dataList = [];
  bool loading = false;

  @override
  void initState() {
    super.initState();
    getArticles();
  }

  Future getArticles() async {
    try {
      setState(() {
        loading = true;
      });
      final list = await FestivalAPI.getArticles(context, Utils.getSolarTermPinyin(widget.festival.name!));
      
      // 先过滤出标题不为空的文章
      final filteredList = list.where((element) => element.title?.isNotEmpty ?? false).toList();
      
      if (filteredList.isNotEmpty) {
        // 打乱列表顺序
        filteredList.shuffle();
        // 取需要的数量（12条或全部，取较小值）
        final count = filteredList.length > 12 ? 12 : filteredList.length;
        setState(() {
          dataList = filteredList.sublist(0, count);
        });
      } else {
        setState(() {
          dataList = [];
        });
      }
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  ///container样式
  BoxDecoration containerStyle() {
    return BoxDecoration(
        color: ColorStyle.themeLightColor,
        border: Border.all(width: 5.w, color: ColorStyle.borderColor),
        borderRadius: BorderRadius.all(Radius.circular(60.w))
    );
  }

  @override
  Widget build(BuildContext context) {
    final dateList = widget.festival.pubDate?.split('月') ?? [];
    final month = dateList[0].padLeft(2, '0');
    final day = dateList[1].split('日')[0].padLeft(2, '0');
    return Scaffold(
      appBar: CommonHeader.appBar(context: context, showActions: false),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: ListView(
        physics: const ClampingScrollPhysics(),
        padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 40.w),
        children: [
          Stack(
            children: [
              ///这里显示问题列表
              Container(
                width: 670.w,
                margin: EdgeInsets.only(top: 20.w),
                padding: EdgeInsets.only(top: 700.w, left: 35.w, right: 35.w, bottom: 20.w),
                decoration: containerStyle(),
                child: loading ? const CommonLoadingCircleWidget() : Wrap(
                  spacing: 10.w,
                  runSpacing: 20.w,
                  children: dataList.asMap().keys.map((index) {
                    return GestureDetector(
                      onTap: () {
                        if (dataList[index].url == null || dataList[index].url == '') return;
                        context.push('/festival_article', extra: {
                          "article": dataList[index]
                        });
                      },
                      child: Container(
                          key: ValueKey(index),
                          width: 285.w,
                          height: 100.w,
                          alignment: Alignment.center,
                          padding: EdgeInsets.symmetric(horizontal: 35.w),
                          decoration: BoxDecoration(
                              color: const Color.fromRGBO(219, 207, 174, 1),
                              borderRadius: BorderRadius.all(Radius.circular(20.w))
                          ),
                          child: Text(dataList[index].title??'', maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 30.sp, color: ColorStyle.textColor))
                      ),
                    );
                  }).toList(),
                ),
              ),
              ///这里显示第一个节气的大图
              Container(
                height: 705.w,
                decoration: containerStyle(),
                child: Stack(
                  children: [
                    Positioned.fill(
                        child: ClipRRect(
                          borderRadius: BorderRadius.all(Radius.circular(55.w)),
                          child: Image.asset('assets/festivals/${widget.festival.name}.jpg', fit: BoxFit.fill),
                        )
                    ),
                    Positioned(
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: Container(
                          height: 130.w,
                          decoration: BoxDecoration(
                              color: ColorStyle.themeLightColor.withOpacity(0.1),
                              borderRadius: BorderRadius.all(Radius.circular(55.w))
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.all(Radius.circular(55.w)),
                            child: BackdropFilter(
                              filter: ImageFilter.blur(
                                sigmaX: 5, // 横向模糊程度
                                sigmaY: 5, // 纵向模糊程度
                              ),
                              child: Container(
                                color: Colors.transparent, // 保持透明，显示模糊效果
                                padding: EdgeInsets.symmetric(horizontal: 60.w),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Row(
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(bottom: 6.w, right: 26.w),
                                          child: CommonShadowTextWidget(txt: widget.festival.name??'', fontSize: 30.sp),
                                        ),
                                        CommonText(txt: '${widget.festival.pubDate}', fontSize: 24.sp),
                                        Container(
                                          width: 2.w,
                                          height: 21.w,
                                          margin: EdgeInsets.symmetric(horizontal: 6.w),
                                          decoration: BoxDecoration(
                                              color: ColorStyle.themeColor,
                                              borderRadius: BorderRadius.all(Radius.circular(1.w))
                                          ),
                                        ),
                                        Expanded(child: CommonText(txt: '农历${widget.festival.priDate}', fontSize: 24.sp),),
                                        Container(
                                          height: 36.w,
                                          padding: EdgeInsets.symmetric(horizontal: 10.w),
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              color: ColorStyle.themeColor,
                                              borderRadius: BorderRadius.all(Radius.circular(18.w))
                                          ),
                                          // child: CommonText(txt: '4天后', fontSize: 20.sp),
                                          child: CommonText(txt: Utils.getDaysFromNow('${widget.festival.pubYear}-$month-$day'), fontSize: 24.sp),
                                        )
                                      ],
                                    ),
                                    Text('${widget.festival.des?.replaceAll('<p>', '').replaceAll('</p>', '')}', overflow: TextOverflow.ellipsis, maxLines: 1, style: TextStyle(fontSize: 24.sp, color: ColorStyle.textColor))
                                  ],
                                ),
                              ),
                            ),
                          ),
                        )
                    )
                  ],
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}
